package com.jcloudsoft.springbootshardingsphere.ShardingAlgorithm;

import com.google.common.collect.ContiguousSet;
import com.google.common.collect.DiscreteDomain;
import com.google.common.collect.Range;
import org.apache.shardingsphere.sharding.api.sharding.complex.ComplexKeysShardingAlgorithm;
import org.apache.shardingsphere.sharding.api.sharding.complex.ComplexKeysShardingValue;

import java.util.Collection;

/**
 * @author wangfei
 * @date 2022-02-16 8:44
 */
public class MyComplexKeysShardingAlgorithm implements ComplexKeysShardingAlgorithm<Long> {
    @Override
    public Collection<String> doSharding(Collection<String> collection, ComplexKeysShardingValue<Long> complexKeysShardingValue) {
        System.out.println(collection);
        System.out.println(complexKeysShardingValue);
        //获取准确值
        Collection userIds = complexKeysShardingValue.getColumnNameAndShardingValuesMap().get("userId");
        Collection ages= complexKeysShardingValue.getColumnNameAndShardingValuesMap().get("age");
        if(userIds != null && !userIds.isEmpty()){
            System.out.println("userId:"+userIds.toArray()[0].toString());
        }
        if(ages != null && !ages.isEmpty()) {
            System.out.println("ages:"+ages.toArray()[0].toString());
        }
        // 获取范围
        Range<Long> userIdRanges = complexKeysShardingValue.getColumnNameAndRangeValuesMap().get("userId");
        Range<Long> ageRanges = complexKeysShardingValue.getColumnNameAndRangeValuesMap().get("age");
        printRange(userIdRanges);
        printRange(ageRanges);

        return collection;
    }

    private void printRange(Range<Long> range){
        if(range == null)
            return;
        System.out.print("[ ");
        for(Long item : ContiguousSet.create(range, DiscreteDomain.longs())) {
            System.out.print(item +" ");
        }
        System.out.println("]");
    }


    @Override
    public void init() {

    }

    @Override
    public String getType() {
        return "CLASS_BASED";
    }
}
